<template>
  <el-dialog :title="dialogTitle[dialogType]" :visible="dialogVisible" :append-to-body="true" @close="handleClose">
    <!--  内层弹窗：树形选择父亲节点 begin  -->
    <el-dialog
      width="30%"
      title="父亲节点"
      :visible.sync="innerVisible"
      append-to-body
    >
      <el-tree
        ref="treeForm"
        :data="treeData"
        :props="defaultProps"
        node-key="id"
        show-checkbox
        check-strictly
        default-expand-all
        @check-change="handleNodeClick"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitParent">确 定</el-button>
      </div>
    </el-dialog>
    <!--  内层弹窗：树形选择父亲节点 end  -->
    <el-form ref="localResource" :rules="rules" :model="localResource" label-position="left" inline class="demo-table-expand" label-width="120px">
      <el-form-item label="资源名称" prop="name">
        <el-input v-model="localResource.name" />
      </el-form-item>
      <el-form-item label="URL" prop="url">
        <el-input v-model="localResource.url" />
      </el-form-item>
      <el-form-item label="Api" prop="api">
        <el-input v-model="localResource.api" />
      </el-form-item>
      <!--      &lt;!&ndash;   后台雪花算法生成id，不需要前端指定   &ndash;&gt;-->
      <!--      <el-form-item label="资源编号" prop="id">-->
      <!--        <el-input v-model.number="localResource.id" />-->
      <!--      </el-form-item>-->
      <el-form-item label="备注">
        <el-input v-model="localResource.remark" />
      </el-form-item>
      <el-form-item label="顺序编号" prop="orderIndex">
        <el-input v-model.number="localResource.orderIndex" />
      </el-form-item>
      <el-form-item label="打开图标" prop="openImg">
        <el-select v-model="localResource.openImg">
          <el-option label="表单图标" value="el-icon-s-order">
            <i class="el-icon-s-order"> 表单图标</i>
          </el-option>
          <el-option label="用户图标" value="el-icon-user">
            <i class="el-icon-user"> 用户图标</i>
          </el-option>
          <el-option label="折叠图标" value="el-icon-s-unfold">
            <i class="el-icon-s-unfold"> 折叠图标</i>
          </el-option>
          <el-option label="菜单图标" value="el-icon-menu">
            <i class="el-icon-menu"> 菜单图标</i>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关闭图标" prop="closeImg">
        <el-select v-model="localResource.closeImg">
          <el-option label="表单图标" value="el-icon-s-order">
            <i class="el-icon-s-order"> 表单图标</i>
          </el-option>
          <el-option label="用户图标" value="el-icon-user">
            <i class="el-icon-user"> 用户图标</i>
          </el-option>
          <el-option label="折叠图标" value="el-icon-s-unfold">
            <i class="el-icon-s-unfold"> 折叠图标</i>
          </el-option>
          <el-option label="菜单图标" value="el-icon-menu">
            <i class="el-icon-menu"> 菜单图标</i>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="子系统" prop="subSystemId">
        <el-select v-model="localResource.subSystemId" placeholder="请选择子系统">
          <el-option v-for="subSystem in subSystemList" :key="subSystem.id" :label="subSystem.name" :value="subSystem.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="父亲节点" prop="parentId">
        <el-button type="primary" :disabled="localResource.subSystemId===null" @click="openInnerDialog">
          {{ formatParentName(localResource.parentName) }}
        </el-button>
      </el-form-item>
      <el-form-item label="是否叶子节点" prop="leaf">
        <el-radio-group v-model.number="localResource.leaf">
          <el-radio label="是" :value="0" />
          <el-radio label="否" :value="1" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="资源类型" prop="resourceType">
        <el-radio-group v-model.number="localResource.resourceType">
          <el-radio label="菜单" :value="0" />
          <el-radio label="按钮" :value="1" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否隐藏" prop="status">
        <el-radio-group v-model.number="localResource.status">
          <el-radio label="是" :value="0" />
          <el-radio label="否" :value="1" />
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getSubSystemList, getSubSystemListBySubSystemId, insertResource, updateResource } from '@/api/resource'

export default {
  name: 'ResourceDialog',
  props: {
    // 弹窗开关
    dialogFlag: {
      type: Boolean,
      default: false
    },
    // 弹窗类型（0-增加 1-编辑）
    dialogType: {
      type: Number,
      default: 0
    },
    // 传入资源信息
    resource: {
      type: Object,
      default: () => ({
        id: -1,
        name: '',
        subSystemId: null,
        subSystemName: '',
        code: '1',
        orderIndex: null,
        parentId: null,
        parentName: '',
        url: '',
        api: '',
        openImg: '',
        closeImg: '',
        resourceType: null,
        remark: '',
        tenantId: 1337940702788714496,
        orgId: 1337955940401545216,
        companyId: null,
        updatedBy: null,
        updatedTime: null,
        status: null,
        version: null
      })
    }
  },
  data() {
    // 自定义校验数字规则
    const checkNumber = (rule, value, callback) => {
      if (!Number.isInteger(value)) {
        callback(new Error('请输入一个整数'))
      }
      callback()
    }
    return {
      dialogVisible: false,
      localResource: { ...this.resource },
      dialogTitle: ['增加资源', '编辑资源'],
      subSystemList: [],
      rules: {
        name: [
          { required: true, message: '请输入资源名称', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入URL', trigger: 'blur' }
        ],
        api: [
          { required: true, message: '请输入Api', trigger: 'blur' }
        ],
        // id: [
        //   { required: true, message: '请输入资源编号', trigger: 'blur' }
        // ],
        orderIndex: [
          { required: true, message: '请输入顺序编号', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        openImg: [
          { required: true, message: '请选择打开图标', trigger: 'blur' }
        ],
        closeImg: [
          { required: true, message: '请选择关闭图标', trigger: 'blur' }
        ],
        subSystemId: [
          { required: true, message: '请选择子系统', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择父亲节点', trigger: 'blur' }
        ],
        leaf: [
          { required: true, message: '请选择是否叶子节点', trigger: 'blur' }
        ],
        resourceType: [
          { required: true, message: '请选择资源类型', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择是否隐藏', trigger: 'blur' }
        ]
      },
      // ---------- 内层树形单选begin ----------
      innerVisible: false,
      checkedId: -1,
      checkedLabel: '',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
      // ---------- 内层树形单选end ----------
    }
  },
  watch: {
    dialogFlag() {
      this.dialogVisible = this.dialogFlag
      this.localResource = { ...this.resource }
      this.localResource.leaf = this.localResource.resourceType === 0 ? '是' : '否'
      this.localResource.resourceType = this.localResource.resourceType === 0 ? '菜单' : '资源'
      this.localResource.status = this.localResource.status === 0 ? '是' : '否'
    },
    // 修改子系统时更新资源树
    'localResource.subSystemId': {
      handler() {
        this.fetchResourceTreeListBySubSystemId()
      }
    }
  },
  created() {
    this.fetchSubSystemList()
  },
  methods: {
    // ---------- 表单共用函数begin ----------
    handleClose() {
      this.$emit('update:dialog-flag', false)
    },
    fetchSubSystemList() {
      getSubSystemList().then(response => {
        this.subSystemList = response.data
      }).catch(() => {})
    },
    // ---------- 表单共用函数end ----------
    // ---------- 提交表单begin ----------
    submitForm() {
      if (this.dialogType === 0) {
        this.submitAddForm()
      } else {
        this.submitEditForm()
      }
    },
    submitAddForm() {
      this.$refs.localResource.validate((valid) => {
        if (valid) {
          this.localResource.leaf = this.localResource.leaf === '是' ? 0 : 1
          this.localResource.resourceType = this.localResource.resourceType === '菜单' ? 0 : 1
          this.localResource.status = this.localResource.status === '是' ? 0 : 1
          insertResource(this.localResource)
            .then(response => {
              console.log('插入资源成功:', response)
              this.$message({
                message: '插入资源成功',
                type: 'success'
              })
              // 清空表单
              this.$refs.localResource.resetFields()
            })
            .catch(error => {
              console.error('插入资源时出错:', error)
              this.$message.error('插入资源时出错')
            })
          this.dialogVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitEditForm() {
      this.$refs.localResource.validate((valid) => {
        if (valid) {
          this.localResource.leaf = this.localResource.leaf === '是' ? 0 : 1
          this.localResource.resourceType = this.localResource.resourceType === '菜单' ? 0 : 1
          this.localResource.status = this.localResource.status === '是' ? 0 : 1
          updateResource(this.localResource)
            .then(response => {
              console.log('编辑资源成功:', response)
              this.$message({
                message: '编辑资源成功',
                type: 'success'
              })
              // 清空表单
              this.$refs.localResource.resetFields()
            })
            .catch(error => {
              console.error('编辑资源时出错:', error)
              this.$message.error('编辑资源时出错')
            })
          this.dialogVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // ---------- 提交表单end ----------
    // ---------- 内层树形单选begin ----------
    openInnerDialog() {
      this.fetchResourceTreeListBySubSystemId()
      this.innerVisible = true
    },
    handleNodeClick(data, checked, node) {
      if (checked === true) {
        console.log(typeof data.id + ': ' + data.id)
        this.checkedId = data.id
        console.log(typeof this.checkedId + ': ' + this.checkedId)
        this.checkedLabel = data.label
        this.$refs.treeForm.setCheckedKeys([data.id])
      } else {
        if (this.checkedId === data.id) {
          this.$refs.treeForm.setCheckedKeys([data.id])
        }
      }
    },
    formatParentName(parentName) {
      if (this.localResource.subSystemId === null) {
        return '请先选择子系统'
      } else if (parentName === '') {
        return '请选择父亲节点'
      } else {
        return parentName
      }
    },
    fetchResourceTreeListBySubSystemId() {
      getSubSystemListBySubSystemId(this.localResource.subSystemId, this.localResource.subSystemName).then(response => {
        this.treeData = response.data
        console.log(this.treeData)
      }).catch(() => {})
    },
    submitParent() {
      this.localResource.parentId = this.checkedId
      this.localResource.parentName = this.checkedLabel
      this.innerVisible = false
    }
    // ---------- 内层树形单选end ----------
  }
}
</script>

<style scoped>
.el-form-item {
  margin-right: 0;
  margin-bottom: 20px;
  width: 50%;
}
</style>
